<template>
  <div class="tracetask-container">
    <v-layout wrap justify-center align-center>
      <v-flex md12 d-flex>
        <v-flex md2 px-2>
          <v-text-field v-model="queryForm.taskNumber" label="活动编号"></v-text-field>
        </v-flex>
        <v-flex md2 px-2>
          <v-text-field v-model="queryForm.buyerNickName" label="买手信息"></v-text-field>
        </v-flex>
        <v-flex md2 px-2>
          <v-select :items="states" v-model="queryForm.orderStatus" label="订单状态"></v-select>
        </v-flex>
        <v-flex md2 px-2>
          <v-btn round class="subTitle" color="primary" @click="onQuery">
            <span>查询</span>
            <v-icon>search</v-icon>
          </v-btn>
        </v-flex>
      </v-flex>

      <!-- table -->
      <v-flex md12 class="elevation-1">
        <v-data-table :headers="headers" :loading="loading" :items="tableData" hide-actions>
          <template v-slot:items="props">
            <td class="text-xs-center">{{ props.item.orderId }}</td>
            <td class="text-xs-center">{{ props.item.taskNumber }}</td>
            <td class="text-xs-center">{{ props.item.platform | Platform }}</td>
            <td class="text-xs-center">{{ props.item.taskType | TaskType }}</td>
            <td class="text-xs-center">{{ props.item.orderStatus | OrderStatus }}</td>
            <td class="text-xs-center">{{ props.item.buyerNickName }}</td>
            <td class="text-xs-center">{{ props.item.orderNumber }}</td>
            <td class="text-xs-center">{{ getTime(props.item.createTime) }}</td>
            <td width="25%" class="text-xs-center mini-button">
              <v-layout wrap justify-center align-center>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="indigo lighten-2"
                    @click="onDetail(props.item)"
                  >
                    <div class="mr-1">查看详情</div>
                  </v-btn>
                </v-flex>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="light-blue"
                    @click="onActivity(props.item)"
                  >
                    <div class="mr-1">查看活动</div>
                  </v-btn>
                </v-flex>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="red lighten-2"
                    @click="onInvalid(props.item)"
                    v-if="props.item.orderStatus === 1"
                  >
                    <div class="mr-1">放弃订单</div>
                  </v-btn>
                </v-flex>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="teal lighten-2"
                    @click="onConfirmOrder(props.item)"
                  >
                    <div class="mr-1">确认订单</div>
                  </v-btn>
                </v-flex>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="green darken-2"
                    @click="onReview(props.item)"
                  >
                    <div class="mr-1">确认评价</div>
                  </v-btn>
                </v-flex>
                <v-flex md4>
                  <v-btn
                    round
                    small
                    outline
                    class="subTitle"
                    color="orange lighten-2"
                    @click="onFailOrder(props.item)"
                  >
                    <div class="mr-1">设为失败订单</div>
                  </v-btn>
                </v-flex>
              </v-layout>
            </td>
          </template>
          <template v-slot:no-data>
            <v-alert :value="true" outline color="warning" icon="info">暂无数据</v-alert>
          </template>
        </v-data-table>

        <v-layout class="pagination-wrapper">
          <v-flex md10 d-flex justify-start align-center>
            <v-flex d-flex md2 justify-start align-center>
              <v-flex md4 class="title-color">显示</v-flex>
              <v-flex md4>
                <v-select
                  @change="onPageOptionChange"
                  :items="pageOptions"
                  v-model="pagination.limit"
                ></v-select>
              </v-flex>
              <v-flex md4 class="title-color">条/页</v-flex>
            </v-flex>
            <v-flex md2 class="title-color">共 {{ pagination.pageCount }} 条数据</v-flex>
            <v-flex md2></v-flex>
            <v-flex md4>
              <v-pagination
                @input="onPageChange"
                :length="pagination.pageCount"
                circle
                total-visible="5"
                v-model="pagination.page"
              />
            </v-flex>
            <v-flex md2></v-flex>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-layout>

    <v-dialog v-model="dialog" max-width="800px">
      <v-card>
        <v-card-title class="headline grey lighten-2"
          primary-title>
          {{ dialogTitle }}
        </v-card-title>
        <v-card-text>
          <!-- 查看评价图片 -->
          <v-layout justify-center align-center v-if="dialogType === 1 || dialogType === 2">
            <v-flex md12>
              <img :src="dialogItem.image" alt="">
            </v-flex>
            <!-- <v-flex
              md8
              class="droppable"
              id="dropPanel"
              @drop="onDrop"
              @dragover="onDragOver"
            >
              <div class="fill-height fill-width">
                <img class="preview-image" :src="imagePreview" alt v-if="imagePreview !== ''" />
              </div>

              <ui-icon icon="cloud-upload fa-lg" v-if="imagePreview === ''" class="cloud-icon"></ui-icon>
              <span
                v-if="imagePreview === ''"
                class="upload-tip title-color"
              >选择图片</span>

              <input
                type="file"
                accept="image/*"
                name="imageInput"
                class="file-input"
                @change="onFileInputChange"
              />
            </v-flex> -->
          </v-layout>
          <v-layout justify-center align-center v-if="dialogType === 3">
            <v-flex md12 v-if="dialogType === 1">
              <!-- <div>订单截图</div> -->
              <div class="mt-2">
                <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[0]" alt />
              </div>
            </v-flex>
            <v-flex md12 v-if="dialogType === 2">
              <!-- <div>评价截图</div> -->
              <div class="mt-2">
                <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[1]" alt />
              </div>
            </v-flex>
            <v-flex md12 v-if="dialogType === 3">
              <v-layout align-center justify-center>
                <v-flex md6>
                  <!-- <div>订单截图</div> -->
                  <div class="mt-2">
                    <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[0]" alt />
                  </div>
                </v-flex>
                <v-flex md6>
                  <!-- <div>评价截图</div> -->
                  <div class="mt-2">
                    <img class="dialog-image" :src="!dialogData.orderImgArr ? '' : dialogData.orderImgArr[1]" alt />
                  </div>
                </v-flex>
          </v-layout>
                </v-flex>
          </v-layout>

        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onDialogConfirm">确认</v-btn>
          <v-btn color="grey darken-1" flat @click="dialog = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="modal" persistent max-width="290">
      <v-card>
        <v-card-title class="title">{{ modalTitle }}</v-card-title>
        <v-card-text class="title">{{ modalContent }}</v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onModalConfirm">确定</v-btn>
          <v-btn color="grey darken-1" flat @click="modal = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { Todo, FileHandler } from "@/api";
import { OrderStatusKV, PageOptions } from "@/utils/constants";
import { KV } from "@/utils/type";
import { forEach } from "lodash";
import { RequestPageVo, ReqTaskOrder, RespFileVo } from "@/api/bean";
import { getTime } from "@/utils/commonUtils";

declare const $Vue: Vue;

@Component
export default class OrderList extends Vue {
  private taskTypes: Array<KV> = [];
  private pageOptions: any = [];
  private states: any = [];

  private queryForm: any = {
    taskNumber: "",
    buyerNickName: "", 
    orderStatus: ''
  };

  private headers: Array<any> = [
    { text: "ID", align: "center", sortable: false, value: "id" },
    { text: "活动编号", align: "center", sortable: false, value: "taskId" },
    { text: "平台名称", align: "center", sortable: false, value: "platform" },
    { text: "任务类型", align: "center", sortable: false, value: "type" },
    { text: "订单状态", align: "center", sortable: false, value: "seller" },
    { text: "买手信息", align: "center", sortable: false, value: "myshop" },
    { text: "订单号", align: "center", sortable: false, value: "orderId" },
    { text: "创建时间", align: "center", sortable: false, value: "createTime" },
    { text: "操作", align: "center", sortable: false, value: "action" },
  ];

  private tableData: any = [{

  }];
  private loading: boolean = false;
  private imagePreview: string = '';

  private dialog: boolean = false;
  private dialogTitle: string = "";
  private dialogType: number = 1;
  private dialogItem: any = {};
  private dialogData: any = {};

  private modal: boolean = false;
  private modalType: number = 1;
  private modalTitle: string = "注意!";
  private modalContent: string = "确认取消订单吗?";
  private modalItem: any = {};
  private isQuery: boolean = false;

  private file: any = null;

  private pagination: any = {
    pageCount: 20,
    page: 1,
    limit: 10,
    offset: 0
  };

  protected mounted() {
    this.getOrderList();
    this.initialize();
  }

  private initialize() {
    this.states = OrderStatusKV.slice();
    this.pageOptions = PageOptions.slice();
  }

  private getTime(date: string) {
    return getTime(date);
  }

  /**
   * 处理订单列表显示 包括图片详情
   */
  private handleOrderList(list: Array<any>) {
    list.forEach((item: any) => {
      let orderImg = null;
      if (item.orderImg) {
        if (item.orderImg.match(/\[/g)) {
          try {
            orderImg = JSON.parse(item.orderImg);
            item.orderImgArr = orderImg;
          } catch (err) {
            console.error(err);
          }
        } else {
          item.orderImgArr = [item.orderImg];
        }
      } else {
        item.orderImgArr = [];
      }
    });
    // console.log(list);
    
    this.tableData = list;
  }

  private onQuery(from?: string) {
    let params: any = {};

    let valid = 0;
    forEach(this.queryForm, (item, key) => {
      item ? (params[key] = item) : valid++;
    });
    if (valid === 3) {
      return this.getOrderList();
      // $Vue.$emit("snackbar", {
      //   message: "请至少填写一个查询条件"
      // });
    }

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }
    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.getOrderList(params);
    this.isQuery = true;
  }

  // 查看详情
  private onDetail(item: any) {
    this.dialogType = 3;
    this.dialogData = item;
    this.dialog = true;
    this.dialogTitle = '订单详情';
  }
  // 查看活动
  private onActivity(item: any) {
    this.dialogType = 4;
    this.dialog = true;
    this.dialogTitle = '活动';

  }
  // 放弃订单
  private onInvalid(item: any) {
    this.modalType = 1;
    this.modal = true;
    this.modalItem = item;
    this.modalContent = "确认放弃该订单吗?";
  } 
  
  // 设为失败订单
  private onFailOrder(item: any) {
    this.modalType = 2;
    this.modal = true;
    this.modalItem = item;
    this.modalContent = "确认将订单设置为失败吗？确定后本佣将直接返给商家！现在设为失败订单不会判断订单是否已经在冻结状态，请谨慎操作！已经跟买家结算的本金和金币不会自动退给商家，需要手工操作（如果还未结算则会返）?";
  }

  // 确认订单 上传图片
  private onConfirmOrder(item: any) {
    this.dialog = true;
    this.dialogType = 2;
    this.dialogTitle = '上传订单截图';
  }

  // 确认评价 上传图片
  private onReview(item: any) {
    this.dialog = true;
    this.dialogType = 1;
    this.dialogTitle = '上传评价截图';
  }

  private onPageChange(page: number) {
    this.pagination.offset = (page - 1) * this.pagination.limit;
    if (!this.isQuery) {
      this.getOrderList();
    } else {
      this.onQuery("wyvonj");
    }
  }

  private onPageOptionChange(value: any) {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private onModalConfirm() {
    if (this.modalType === 1) {
      // 废弃订单
      this.invalidOrder();
    } else if (this.modalType === 2) {
      // 设为失败订单
      this.invalidOrder();
    }
  }

  private onDialogConfirm() {
    // 确认 订单 或 评价截图
    if (this.dialogType === 1) {
      // if (this.file !== null) {
      //   this.uploadFile();
      // } else {
      //   return $Vue.$emit("snackbar", {
      //     message: '请选择图片文件!',
      //   });
      // }
      this.dialog = false;
      // this.saveReview();
    } else if (this.dialogType === 2) {
      this.dialog = false;
      this.confirmOrder();
    } else {
      this.dialog = false;
    }
  }

  private onDrop(ev: any) {
    ev.preventDefault();
    const file = ev.dataTransfer.files[0];
    if (!file.name.match(/\.jp(e)g|png/g)) {
      return alert("请拖入图片文件");
    }
    this.handleImageFile(file);
  }

  private onDragOver(ev: DragEvent) {
    ev.preventDefault();
    return false;
  }

  private onFileInputChange(ev: any) {
    let file = ev.target.files[0];
    this.handleImageFile(file);
  }

  private handleImageFile(file: File) {
    const reader = new FileReader();
    this.file = file;
    reader.onload = (ev: any) => {
      this.imagePreview = ev.target.result;
    };
    reader.readAsDataURL(file);
  }

  /**
   * 图片上传完成
   */
  private handleImageUploaded(data: RespFileVo) {
    let fileUrl = data.fileUrl;
    if (this.dialogType === 1) {
      // 评价截图
      // this.saveReview(fileUrl);
    } else if (this.dialogType === 2) {
      // this.confirmOrder();
    }
  }

  /**
   * 获取订单列表  查询订单
   */
  private async getOrderList(queryForm?: any) {
    let params: ReqTaskOrder = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
    };
    if (queryForm) {
      params = queryForm;
    }
    const { data } = await Todo.getOrderList.r(params);
    console.log("getOrderList", data);
    if (data.result === 0) {
      let $data = data.data;
      this.handleOrderList($data.dataList);

      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  /**
   * 修改任务状态
   */
  private async saveReview(img: string) {
    const params: ReqTaskOrder = {
      orderId: this.dialogItem.orderId,
      img,
    };
    const { data } = await Todo.saveReview.r(params);
    console.log("saveReview", data);
    $Vue.$emit("snackbar", {
        message: data.message
    });
    if (data.result === 0) {
      //
    } else {

    }
  }

  /**
   * 确认订单
   */
  private async confirmOrder() {
    const params = {
      orderId: this.dialogItem.orderId,
    };
    const { data } = await Todo.confirmOrder.r(params);
    console.log("saveReview", data);
    $Vue.$emit("snackbar", {
        message: data.message
      });
    if (data.result === 0) {
      //
    } else {
    }
  }

  /**
   * 废弃订单
   */
  private async invalidOrder() {
    const params = {
      orderId: this.modalItem.orderId,
    };
    const { data } = await Todo.invalidOrder.r(params);
    console.log("saveReview", data);
    $Vue.$emit("snackbar", {
        message: data.message
      });
    if (data.result === 0) {
      //
    } else {
    }
  }

  private async uploadFile() {
    const params: FormData = new FormData();
    params.append('file', this.file);
    const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      },
    };
    const { data } = await FileHandler.uploadFile.r(params, config);
    console.log("uploadFile", data);
    if (data.result === 0) {
      // 图片上传完成后的处理
      this.handleImageUploaded(data.data[0]);
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

}
</script>

<style lang="less" scoped>
.tracetask-container {
  width: 100%;
  height: 100%;
}

.pagination-wrapper {
  background: white;
  border-top: 1px solid #d4d4d4;
}

.droppable {
  border-radius: 4px;
  height: 8rem;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
  .preview-image {
    height: 100%;
  }
  .upload-tip {
    margin: 1rem;
  }
  .cloud-icon {
    margin-top: 2rem;
  }

  .file-input {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    left: 0;
    top: 0;
    &:hover {
      cursor: pointer;
    }
  }
}
#preview {
  height: 18rem;
  border: 1px dashed #888;
  border-radius: 8px;
}

.dialog-image {
  height: 10rem;
}
</style>


